<?php

/**
 * 湖南芒果tv的boss对接api
 * 返回格式不对返回502，超时返回504
 */
class boss {

        //	循环调取接口次数
        static $post_num = 0;
        //	失败情况下调取接口总次数	
        private $post_total = 3;
        //单例保存对象
        static public $obj = null;
        //连接等待时间,0不等待
        public $connect_time_out = 10;
        //设置curl允许执行的最长秒数
        public $time_out = 10;
        //url基础地址
        public $url = "";
        //url端口
        public $port = "";
        //url页面地址
//	public $url_page_url=array(
//		"auth"=>"http://58.83.191.25/OTTBossApi/auth.ashx",
//		"playauth"=>"http://58.83.191.25/OTTBossApi/playauth.ashx",
//		"liveadd"=>"http://58.83.191.25/OTTBossApi/liveadd.ashx",
//		"getplayurl"=>"http://58.83.191.25/OTTBossApi/GetPlayUrl.ashx",
//		"livedel"=>"http://58.83.191.25/OTTBossApi/livedel.ashx",
//		"getassets"=>"http://58.83.191.25/OTTBossApi/GetClipsBySvcId.ashx",
//		"auth_by_token"=>"http://58.83.191.25/OTTBossApi/TokenAuth.ashx",
//		//add guanghu
//		"get_svclist"=>"http://58.83.191.25/OTTBossApi/GetSvcList.ashx",
//		"get_curlist"=>"http://58.83.191.25/OTTBossApi/GetUserCurPayList.ashx",
//		"get_paylist"=>"http://58.83.191.25/OTTBossApi/GetPayList.ashx",
//		"auto_buy"=>"http://58.83.191.25/OTTBossApi/SetSvcAuto.ashx",
//		"get_userlist"=>"http://58.83.191.25/OTTBossApi/GetUserPayList.ashx",
//		//测试请将pay.hunantv.com绑定在58.83.191.30
//		
//		"get_buy_order"=>"http://alpha.pay.hunantv.com/api/samsung/buy",
//		"get_pay"=>"http://alpha.pay.hunantv.com/api/samsung/pay",
//		"get_consume"=>"http://alpha.pay.hunantv.com/api/samsung/consume",
//		"get_order_status"=>"http://alpha.pay.hunantv.com/api/samsung/order_status",
//		"get_record"=>"http://alpha.pay.hunantv.com/api/samsung/record",
//		"get_account"=>"http://alpha.pay.hunantv.com/api/samsung/account",
//		//add 易联
//		"get_payeco"=>"http://alpha.pay.hunantv.com/api/samsung/payeco",
//		"get_history"=>"http://alpha.pay.hunantv.com/api/samsung/payeco_habit",
//		
//		/*
//		"get_buy_order"=>"http://beta.pay.hunantv.com/api/samsung/buy",
//		"get_pay"=>"http://beta.pay.hunantv.com/api/samsung/pay",
//		"get_consume"=>"http://beta.pay.hunantv.com/api/samsung/consume",
//		"get_order_status"=>"http://beta.pay.hunantv.com/api/samsung/order_status",
//		"get_record"=>"http://beta.pay.hunantv.com/api/samsung/record",
//		"get_account"=>"http://beta.pay.hunantv.com/api/samsung/account",
//		 */
//		//add yyp
//		'get_boss'=>'https://idp2.hunantv.com',
//		'get_boss_code' => 'http://idp2.hunantv.com',
//		'get_boss_check_dcode' => 'http://idp2.hunantv.com/notify',
//		'get_send'=>'http://idp2.hunantv.com/api2/outer.php',
//	);

        public $url_page_url;
        //CURL句柄
        private $ch = null;
        private $log_enable = TRUE;

        private function __construct($url = "", $port = "80") {
                $this->port = $port;
                $this->url = $url;
                $this->ch = curl_init();
                //初始化
        }

        static public function get() {
                if (self::$obj === null) {
                        self::$obj = new boss();
                        self::$obj->url_page_url = g_cms_config::get_g_config_value("g_boss_url");
                }
                return self::$obj;
        }

        /**
         * 获取媒资列表
         * @param 
         * 参数组array(
         * "svc_item_id"=>片单ID，
         * "page_index"=>页数，
         * "page_size"=>分页大小，
         * "sort"=>new/hot（最新/最热）默认为新，
         * "token"=>认证串，
         * ）
         * @return 
         * array(
         * "ret"=>回应码
         * "reason"=>说明码
         * "recordcount"=>记录总数
         * "data"=>array()ID数组
         * ）
         */
        public function get_assets($params = array()) {
                $params['sort'] = empty($params['sort']) ? 'new' : $params['sort'];
                $url = $this->url_page_url["getassets"];
                $re = $this->post($url, $params);
                //		写日志
                $this->write_log($url, $params, $re);

                return $re;
        }

        /**/

        public function get_mgtv_pay($key, $params = array()) {
                $url = $this->url_page_url[$key];
                $re = $this->post($url, $params);
                $this->write_log($url, $params, $re);
                return $re;
        }

        /**
         * 认证TOKEN接口
         * @param string $mode认证模式，ott_tv 互联网电视
         * @param array $params，参数组array("mode"=>认证模式,"tv_id"=>电视ID[设备ID],"net_id"=>入网ID,"mac_id"=>MAC地址,"token"=>token密匙)
         */
        public function auth_by_token($params = array()) {
                $url = $this->url_page_url["auth_by_token"];
                //调试yxt2013年3月11日10:02:27，去芒果tvboss检验下面2行用于计算执行时间上线之后删除
                list($usec, $sec) = explode(' ', microtime());
                $GLOBALS['start_mgtv_auth_mac'] = ((float) $usec + (float) $sec);

                $re = $this->post($url, $params);

                //调试yxt下面7行用于计算执行时间，上线之后删除
                list($usec, $sec) = explode(' ', microtime());
                $GLOBALS['end_mgtv_auth_mac'] = ((float) $usec + (float) $sec);
                foreach ($params as $key => $val) {
                        $s.="{$key}={$val}&";
                }
                $s = trim($s, "&");
                $GLOBALS['mgtv_url_auth_mac'] = $url . "?" . $s;
                //		写日志explode
                $this->write_log($url, $params, var_export($re, true));
                //		var_dump($params,$re);die();
                return $re;
        }

        private function get_client_ip() {
                if (getenv('HTTP_CLIENT_IP')) {
                        $client_ip = getenv('HTTP_CLIENT_IP');
                } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
                        $client_ip = getenv('HTTP_X_FORWARDED_FOR');
                } elseif (getenv('REMOTE_ADDR')) {
                        $client_ip = getenv('REMOTE_ADDR');
                } else {
                        $client_ip = $_SERVER['REMOTE_ADDR'];
                }
                return $client_ip;
        }

        /**
         * 认证接口
         * @param string $mode认证模式，ott_tv 互联网电视
         * @param array $params，参数组array("mode"=>认证模式,"tv_id"=>电视ID[设备ID],"net_id"=>入网ID,"mac_id"=>MAC地址,"token"=>token密匙)
         */
        public function auth($params = array()) {
                $url = $this->url_page_url["auth"];
                //调试yxt2013年3月11日10:02:27，去芒果tvboss检验下面2行用于计算执行时间上线之后删除
                list($usec, $sec) = explode(' ', microtime());
                $GLOBALS['start_mgtv_auth'] = ((float) $usec + (float) $sec);
                $params['user_ip'] = $this->get_client_ip();
                $re = $this->post($url, $params);
                //调试yxt下面7行用于计算执行时间，上线之后删除
                list($usec, $sec) = explode(' ', microtime());
                $GLOBALS['end_mgtv_auth'] = ((float) $usec + (float) $sec);
                foreach ($params as $key => $val) {
                        $s.="{$key}={$val}&";
                }
                $s = trim($s, "&");
                $GLOBALS['mgtv_url_auth'] = $url . "?" . $s;
                //		写日志
                $this->write_log($url, $params, var_export($re, true));
                //		var_dump($params,$re);die();
                return $re;
        }

        /**
         * 获取影片定价信息
         * @param string $token
         * @param array $params参数组array("token"=>token,"user_id"=>用户id,"tv_id"=>电视di,"content_id"=>内容id,"content_type"=>0点播1直播)
         */
        public function play_auth($params = array()) {
                $url = $this->url_page_url["playauth"];
                //调试yxt2013年3月11日10:02:27，去芒果tvboss检验下面2行用于计算执行时间上线之后删除
                list($usec, $sec) = explode(' ', microtime());
                $GLOBALS['start_mgtv_play_auth'] = ((float) $usec + (float) $sec);

                $res = $this->post($url, $params);
                //调试yxt下面7行用于计算执行时间，上线之后删除
                list($usec, $sec) = explode(' ', microtime());
                $GLOBALS['end_mgtv_play_auth'] = ((float) $usec + (float) $sec);
                $s = '';
                foreach ($params as $key => $val) {
                        $s.="{$key}={$val}&";
                }
                $s = trim($s, "&");
                $GLOBALS['mgtv_play_auth_url'] = $url . "?" . $s;
                //写日志
                $this->write_log($url, $params, var_export($res, true));
                return $res;
        }

        /**
         * 直播添加修改成功通知计费平台
         * @param string $params,array("live_id"=>直播id,"live_name"=>直播名称,"live_type"=>直播类型TSTV/LIVE)
         */
        public function live_add($params = array()) {
                $url = $this->url_page_url["liveadd"];
                $res = $this->post($url, $params);
                //写日志
                $this->write_log($url, $params, $res);
                return $res;
        }

        /**
         * 直播删除成功通知计费平台
         * @param array $params:array("live_id"=>直播id)
         */
        public function live_del($params = array()) {
                $url = $this->url_page_url["livedel"];
                $res = $this->post($url, $params);
                //写日志
                $this->write_log($url, $params, $res);
                return $res;
        }

        /**
         * 获取播放串地址
         * @param array $params:array(
         * "user_id"=>用户id
         * "user_ip"=>用户ip
         * "file_id"=>片源导入id -->非平台id 为导入ID
         * "content_id"=>平台片源id
         * "content_url"=>片源物理路径 URL编码
         * "time_limit"=>预备时间
         * )
         */
        public function get_play_url($params = array()) {
                //		echo "<pre>";print_r($params);die();
                $url = $this->url_page_url["getplayurl"];


                //调试yxt2013年3月11日10:02:27，去芒果tvboss检验下面2行用于计算执行时间上线之后删除
                list($usec, $sec) = explode(' ', microtime());
                $GLOBALS['start_mgtv'] = ((float) $usec + (float) $sec);
                list($usec, $sec) = explode(' ', microtime());
                $GLOBALS['start_mgtv_get_url'] = ((float) $usec + (float) $sec);

                $res = $this->post($url, $params);
                //调试yxt下面7行用于计算执行时间，上线之后删除
                list($usec, $sec) = explode(' ', microtime());
                $GLOBALS['end_mgtv'] = ((float) $usec + (float) $sec);
                $GLOBALS['end_mgtv_get_url'] = ((float) $usec + (float) $sec);
                foreach ($params as $key => $val) {
                        $s.="{$key}={$val}&";
                }
                $s = trim($s, "&");
                $GLOBALS['mgtv_url'] = $url . "?" . $s;
                $GLOBALS['mgtv_get_play_url'] = $url . "?" . $s;


                //写日志
                $this->write_log($url, $params, var_export($res, true));

                return $res;
        }

        /**
         * @time 2013.4.29
         * @author yyp
         * 用户中心登录接口 
         * 手机号绑定
         * 找回密码
         * 修改密码
         * 用户注册
         */
        public function mgtv_api($url_parame, $status = 0) {
                
                $url_parame_data = array();
				$parame_arr = explode("&",$url_parame);				
				foreach ($parame_arr as $value) {
					$d = explode("=",$value);
					$url_parame_data[$d[0]] = $d[1];
				}
					
					
                $ret_data = array();
                include_once(NPDIR . DIRECTORY_SEPARATOR . 'np_http_curl.class.php');
                $http_client = new np_http_curl_class();
                $json_data = null;
                $http_code = null;
                if ($status == 1) {
                        $url = $this->url_page_url['get_boss_code'] . '/?' . $url_parame;
                } else if ($status == 2) {
                        $url = $this->url_page_url['get_boss_check_dcode'] . '/?' . $url_parame;
                        $json_data = @file_get_contents($url);
                        if ($json_data) {
                                $ret_data = json_decode($json_data, true);
                        }
                        $this->write_log($url, $url_parame_data, $json_data);
                        return $ret_data;
                } else {
                        $url = $this->url_page_url['get_boss'] . '/?' . $url_parame;
                }

                for ($i = 0; $i < 2; $i++) {
                        $json_data = $http_client->post($url, $url_parame);
                        $http_code = $http_client->curl_getinfo['http_code'];
                        if ($http_code != 200) {
                                continue;
                        } else {
                                break;
                        }
                }
                if ($json_data && $http_code && $http_code == 200) {
                        $ret_data = json_decode($json_data, true);
                }
				
				
				
				
                $this->write_log($url, $url_parame_data, $ret_data);
                $arr = array(
                    'mode' => 'ott_tv',
                    'tv_id' => $_GET['nns_device_id'],
                    'net_id' => $_GET['nns_net_id'],
                    'mac_id' => $_GET['nns_mac_id'],
                    'token' => $ret_data['msg']['ticket'],
                    'version' => $_GET['nns_version'],
                    'ex_data' => $_GET['nns_ex_data'],
                );
                if ($_GET['nns_func'] == 'check_valid_by_login' || $_GET['nns_func'] == 'register') {
                        $ar_data = $this->auth_by_token($arr);
                        $bind_mobile = $ret_data['msg']['userinfo'];
                        $ar_data['bind_mobile'] = $bind_mobile['mobile'];
                        $ar_data['reason'] = $ret_data['reason'];
                        $ar_data['error_code'] = $ret_data['status'];
						$ar_data['auth_code'] = $ret_data['err'];
                        return $ar_data;
                } else {
                        return $ret_data;
                }
        }

        /**
         *
         * @time 2013.4.29 
         * @author yyp
         * 短信验证码请求接口
         */
        public function mgtv_modile_send_api($url_parame) {

                if ($_GET['nns_type'] == 'bind_mobile') {
                        $url = $this->url_page_url['get_send'] . '?' . $url_parame;
                } else {
                        $url = $this->url_page_url['get_boss'] . '/?' . $url_parame;
                }

                $ret_data = array();
                include_once(NPDIR . DIRECTORY_SEPARATOR . 'np_http_curl.class.php');
                $http_client = new np_http_curl_class();

                $json_data = null;
                $http_code = null;
                for ($i = 0; $i < 2; $i++) {
                        $json_data = $http_client->get($url);
                        $http_code = $http_client->curl_getinfo['http_code'];
                        if ($http_code != 200) {

                                continue;
                        } else {
                                break;
                        }
                }


                if ($json_data && $http_code && $http_code == 200) {
                        $ret_data = json_decode($json_data, true);
                }
                //echo '<pre>';
                //print_r($ret_data);die;
                $url_parame_data = array();
				$parame_arr = explode("&",$url_parame);				
				foreach ($parame_arr as $value) {
					$d = explode("=",$value);
					$url_parame_data[$d[0]] = $d[1];
				}
                if ($_GET['nns_type'] == 'bind_mobile') {
                        $this->write_log($this->url_page_url['get_send'], $url_parame_data, $ret_data);
                        return $ret_data;
                } else {
                        $this->write_log($this->url_page_url['get_boss'], $url_parame_data, $ret_data);
                        return $ret_data;
                }
        }
        /**
         * 湖南有线n1_b登录认证
         * @param $params array(
         * mode ：ott_tv
         * device_id 
         * mac_id
         * user_ip
         * )
         */
        public function auth_hncscatv($params){
                $ret_data = array();
                include_once(NPDIR . DIRECTORY_SEPARATOR . 'np_http_curl.class.php');
                $http_client = new np_http_curl_class();
                
                $url = $this->url_page_url["auth_hncscatv"];

                $json_data = null;
                $http_code = null;
                for ($i = 0; $i < 2; $i++) {
                        $json_data = $http_client->post($url, $params);
                        $http_code = $http_client->curl_getinfo['http_code'];
                        if ($http_code != 200) {

                                continue;
                        } else {
                                break;
                        }
                }


                if ($json_data && $http_code && $http_code == 200) {
                        $ret_data = json_decode($json_data, true);
                }                
               
                //写日志
                $this->write_log($url, $params, $ret_data);
                return $ret_data;
        }
        private function post($url, $params) {
                //unset($params["token"],$params["content_url"]);
                //设置CURL连接的端口
                curl_setopt($this->ch, CURLOPT_PORT, $this->port);
                //设置连接等待时间,0不等待
                curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $this->connect_time_out);
                //设置curl允许执行的最长秒数
                curl_setopt($this->ch, CURLOPT_TIMEOUT, $this->time_out);
                //发送一个常规的POST请求，类型为：application/x-www-form-urlencoded
                curl_setopt($this->ch, CURLOPT_POST, true);
                //设置POST字段值
                curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params);
                //设置请求的URL
                curl_setopt($this->ch, CURLOPT_URL, $url);
                curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
                //开始执行请求
                $result = curl_exec($this->ch);


                //接口次数+1
                self::$post_num++;
                //写日志
                $this->write_log($url, $params, array('num' => self::$post_num, 'data' => var_export($result, true)));
                //如果超时返回504
                if ($result === false) {
                        if (self::$post_num == $this->post_total) {
                                self::$post_num = 0;
                                return 504;
                        } else {
                                return $this->post($url, $params);
                        }
                }
                $result = json_decode($result, true);
                if (!is_array($result)) {
                        //			return array('ret'=>0);
                        if (self::$post_num == $this->post_total) {
                                self::$post_num = 0;
                                return 502;
                        } else {
                                return $this->post($url, $params);
                        }
                }

                //		$result['ret']='0';
                //		return $result;

                if ($result['ret'] == '0' || $result['err'] == '0') {
                        self::$post_num = 0;
                        return $result;
                } else {

                        if (stripos($url, $this->url_page_url['auth']) !== FALSE && $result['ret'] == '4') {
                                self::$post_num = 0;
                                return $result;
                        }

                        if (self::$post_num == $this->post_total) {
                                self::$post_num = 0;
                                return $result;
                        } else {
                                return $this->post($url, $params);
                        }
                }
        }

        /**
         * 得到错误信息
         * @return string
         */
        public function error() {
                return curl_error($this->ch);
        }

        /**
         * 得到错误代码
         * @return int
         */
        public function errno() {
                return curl_errno($this->ch);
        }

        /**
         * 析构方法
         */
        public function __destruct() {
                //关闭CURL
                curl_close($this->ch);
        }

        /**
         * yxt2013年3月11日11:07:25写日志
         * @param string $post_url:请求url
         * @param array	 $params:请求参数
         * @param array  $res请求返回的结果数组
         */
        private function write_log($post_url, $params, $res) {

                if ($this->log_enable === FALSE)
                        return;

                $log_boss_dir = dirname(dirname(dirname(__FILE__))) . '/data/log/mgtv_boss/';
                if (!file_exists($log_boss_dir)) {
                        mkdir($log_boss_dir, 0777, TRUE);
                }
                $handle = fopen($log_boss_dir . date('Y-m-d') . $_SERVER["REMOTE_ADDR"] . ".txt", "a");
                fwrite($handle, "################################" . date("Y-m-d H:i:s", time()) . "nns_func=" . $_REQUEST['nns_func'] . "\r\n");
                if (is_array($params)) {
                        $p = '';
                        foreach ($params as $key => $val) {
                                $p.="{$key}={$val}&";
                        }
                        $p = trim($p, "&");
                }
                fwrite($handle, "POST_URL:\r\n{$post_url}?{$p}\r\n" . "RETURN:\r\n");
                if (is_array($res)) {
                        foreach ($res as $key => $val) {
                                fwrite($handle, $key . '=' . $val . "\r\n");
                        }
                } else {
                        fwrite($handle, 'value=NULL' . "\r\n");
                }
                fclose($handle);
        }

}
